package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.util.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@RocketMQMessageListener(
        consumerGroup = MQConstants.SECKILL_ORDER_GROUP,
        topic = MQConstants.SECKILL_ORDER,
        selectorType = SelectorType.TAG,
        selectorExpression = MQConstants.CREATE_ORDER_TAG
)
@Component
public class OrderCreateMQListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private IOrderInfoService orderInfoService;
    @Override
    public void onMessage(OrderMessage message) {
        //开始下单服务
        //封装消息
        String orderNO = null;
        String uuid = message.getUuid();
        Long seckillId = message.getSeckillId();
        Map<String,Object> map=new HashMap<>();
        map.put("uuid",uuid);
        map.put("seckillId", seckillId);
        try {
            orderNO = orderInfoService.doSeckill(message.getUserId(),seckillId);
            map.put("code",200);
            map.put("data", orderNO);
            System.out.println("下单成功, 开始创建订单通知"+orderNO);
            rocketMQTemplate.syncSend(MQConstants.ORDER_SUCCESS_DEST, map);
        } catch (Exception e) {
            e.printStackTrace();
            //处理失败通知用户
            map.put("msg", 200);
            map.put("code", orderNO);
            map.put("uuid",uuid);
            System.out.println("下单失败, 开始创建订单通知");
            rocketMQTemplate.syncSend(MQConstants.ORDER_FAIL_DEST, map);
        }
    }
}

